<template>
  <el-dialog
    :visible.sync="visible"
    top="30px"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="data" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="用户名" prop="userName">
        <el-input placeholder="用户名" class="form-control-ml" v-model="data.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" v-if="!type" prop="password">
        <el-input
          type="password"
          placeholder="密码"
          class="form-control-ml"
          v-model="data.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" v-if="!type" prop="password2">
        <el-input
          type="password"
          placeholder="再次输入密码"
          class="form-control-ml"
          v-model="data.password2"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <select-dept :clearable="false" class="form-control-ml" v-model="data.deptId"></select-dept>
      </el-form-item>
      <el-form-item label="角色" prop="job" v-if="data.job !== 'org_corp'">
        <select-bank-job
          :clearable="false"
          ref="job"
          v-model="data.job"
          class="form-control-ml"
        ></select-bank-job>
      </el-form-item>

      <el-form-item label="权限" prop="scopes" v-if="hasAuth">
        <select-org-auth
          :clearable="false"
          :auth-type="0"
          :org-type="orgClass"
          v-model="data.scopes"
          :filter="orgAuthFilter"
          @getAllAuth="handleGetAllAuth"
        ></select-org-auth>
      </el-form-item>

      <el-form-item label="姓名" prop="realName">
        <el-input placeholder="姓名" class="form-control-ml" v-model="data.realName"></el-input>
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          placeholder="手机号码"
          class="form-control-ml"
          v-model="data.phoneNumber"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-input placeholder="身份证号" class="form-control-ml" v-model="data.idCard"></el-input>
      </el-form-item>
      <el-form-item label="所属地">
        <select-address
          v-model="data.addressCode"
          auto-top
          placeholder="选择地址"
          class="form-control-ml"
        ></select-address>
      </el-form-item>
      <el-form-item label="地址详情">
        <el-input
          placeholder="地址详情"
          class="form-control-ml"
          v-model="data.addressDetail"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证照片">
        <ul class="list-inline">
          <li class="list-inline-item">
            <upload-oss
              single-image
              ref="uploadFront"
              accept="image/*"
              :file-list="idImgFront"
              :on-complete="handleUploadFront"
            ></upload-oss>
            <div class="text-muted text-center">身份证正面</div>
          </li>
          <li class="list-inline-item">
            <upload-oss
              single-image
              ref="uploadBack"
              accept="image/*"
              :file-list="idImgBack"
              :on-complete="handleUploadBack"
            ></upload-oss>
            <div class="text-muted text-center">身份证反面</div>
          </li>
        </ul>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保 存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUser, putUser, createUser } from '@/common/api/auth'
import { phoneValidator } from '@/common/plugins/validator'

import SelectDept from '@/components/select/SelectDept'
import SelectAddress from '@/components/select/SelectAddress'
import SelectBankJob from '@/bank/components/select/SelectBankJob'
import SelectOrgAuth from '@/cadmin/components/select/SelectOrgAuth'

import { passWordValidator } from '@/common/plugins/validator'

export default {
  components: {
    SelectBankJob,
    SelectDept,
    SelectAddress,
    SelectOrgAuth,
  },

  props: {
    visible: Boolean,
    userData: Object,
    userId: String,
  },

  data() {
    let validateName = (rule, value, callback) => {
      if (!/^[0-9a-zA-Z\-_]*$/g.test(value)) {
        callback(new Error('用户名只能由英文、数字、下划线组成'))
      } else {
        callback()
      }
    }
    let validatePass = (rule, value, callback) => {
      if (value !== this.data.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      data: {
        userName: '',
        deptId: '',
        job: '',
        realName: '',
        phoneNumber: '',
        idCard: '',
        idCardImgStr: '',
        idCardImg: '',
        password: '',
        remark: '',
        password2: '',
        jobName: '',
        scopes: '',
      },
      initData: {},
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' },
        ],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phoneNumber: [{ validator: phoneValidator, trigger: 'blur' }],
        job: [{ required: true, message: '请选择角色', trigger: 'change' }],
        deptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          { validator: passWordValidator, trigger: 'blur' },
        ],
        password2: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
      },
      loading: false,
      idImgFront: [],
      idImgBack: [],
      uploadImages: [],
      clientId: '',

      hasAuth: true,
    }
  },

  computed: {
    ...mapGetters(['org', 'user']),
    orgClass() {
      return this.org.clientOrgClass
    },
    id() {
      return this.userId || this.userData ? this.userData.userId : ''
    },
    type() {
      return !!this.id
    },

    // 限率业务上报权限
    hasHndReportAuth() {
      return this.user.scopeArr.includes('indoneBO')
    },
  },

  watch: {
    userId() {
      this.getData()
    },
    userData: {
      handler: function () {
        this.getData()
      },
      deep: true,
    },
  },

  created() {
    this.initData = { ...this.data }
    this.clientId = this.$utils.getClientId()
    this.getData()
  },

  mounted() {},

  methods: {
    getData() {
      if (this.userData) {
        this.initForm(this.userData)
      } else if (this.userId) {
        this.loading = true
        getUser({
          userId: this.userId,
          clientId: this.clientId,
        })
          .then(res => {
            this.initForm(res.data)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },

    initForm(data) {
      this.data = { ...data }
      if (!this.data.addressCode) {
        this.data.addressCode = this.$utils.getAddressCode()
      }
      if (data.idCardImg) {
        this.idImgFront = [{ url: data.idCardImg[0], name: '' }]
        this.idImgBack = [{ url: data.idCardImg[1], name: '' }]
      }
    },

    beforeClose() {
      this.data = { ...this.initData }
      this.$refs.form.clearValidate()
      this.$emit('update:visible', false)
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$refs.uploadFront.submit()
        } else {
          this.$message.warning('输入错误，请重新输入！')
        }
      })
    },

    // 过滤权限
    orgAuthFilter(item) {
      // 如果组织没有限率上报权限，过滤掉个人的限率上报权限
      return this.hasHndReportAuth ? true : item.scope_value !== 'indoneBI'
    },

    // 如果没有权限列表选择，隐藏表单
    handleGetAllAuth(list) {
      this.hasAuth = list.length > 0
    },

    handleUploadFront(images) {
      this.uploadImages = [images && images.length ? images[0].url : '']
      this.$refs.uploadBack.submit()
    },

    handleUploadBack(images) {
      this.uploadImages.push(images && images.length ? images[0].url : '')
      if (!this.uploadImages.every(img => img === '')) {
        this.data.idCardImg = `["${this.uploadImages.join('","')}"]`
      }
      if (this.type) {
        this.putUser()
      } else {
        this.postUser()
      }
    },

    putUser() {
      this.loading = true
      putUser({
        jobName: this.$refs.job ? this.$refs.job.getJobName() : this.data.jobName,
        realName: this.data.realName,
        phoneNumber: this.data.phoneNumber,
        deptId: this.data.deptId,
        job: this.data.job,
        idCard: this.data.idCard,
        idCardImgStr: this.data.idCardImg,
        clientId: this.clientId,
        userId: this.id,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        scopes: this.data.scopes,
        userName: this.data.userName,
      })
        .then(() => {
          this.actionSuccess()
        })
        .catch(err => {
          const message = (err && err.data && err.data.errorDescription) || ''
          this.$message.error(`修改员工账号失败，${message}！`)
        })
        .then(() => {
          this.loading = false
        })
    },

    postUser() {
      let data = {
        userName: this.data.userName,
        password: this.data.password,
        realName: this.data.realName,
        phoneNumber: this.data.phoneNumber,
        remark: this.data.remark,
        idCard: this.data.idCard,
        clientId: this.clientId,
        job: this.data.job,
        deptId: this.data.deptId,
        jobName: this.$refs.job.getJobName(),
        idCardImgStr: this.data.idCardImg,
        addressCode: this.data.addressCode,
        addressDetail: this.data.addressDetail,
        scopes: this.data.scopes,
      }
      this.loading = true
      createUser(data)
        .then(() => {
          this.actionSuccess()
        })
        .catch(err => {
          const message = (err && err.data && err.data.errorDescription) || ''
          this.$message.error(`添加账号账号失败, ${message}！`)
        })
        .then(() => {
          this.loading = false
        })
    },

    actionSuccess() {
      this.$message.success(`${this.type ? '修改' : '添加'}成功！`)
      this.$emit('success', true)
      this.beforeClose()
    },
  },
}
</script>

<style scoped>
.form-sl {
  width: 197px;
}
</style>
